package com.xiaoxueqi.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoxueqi.entity.Question;
import com.xiaoxueqi.entity.QuestionBank;
import com.xiaoxueqi.mapper.QuestionBankMapper;
import com.xiaoxueqi.mapper.QuestionMapper;
import com.xiaoxueqi.service.QuestionRequestService;
import com.xiaoxueqi.utils.CertificateUtil.DateTimeUtil;
import lombok.RequiredArgsConstructor;
import net.sf.json.JSONException;
import okhttp3.*;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
@Transactional
public class QuestionRequestImpl extends ServiceImpl<QuestionMapper,Question>implements QuestionRequestService{
    private QuestionMapper questionMapper;


    private final QuestionBankMapper questionBankMapper;

    @Override
    public  String questionRequestService(Question question) throws IOException {
        //根据题目（模板）来生成对应的请求语句
        String qutype=new String("");
        switch (question.getQuType()) {
            case 1:
                qutype="四选一选择题";
                break;
            case 2:
                qutype="四选多选择题";
                break;
            case 3:
                qutype="判断题";
                break;
            default:
                qutype="简答题";
        }
        String example=new String();
        switch (question.getQuType()) {
            case 1:
                example="具体题目：Java是一种：" +
                        "A.操作系统" +
                        "B.编程语言" +
                        "C.数据库管理系统" +
                        "D.网络浏览器" +
                        "正确答案：B。" ;
                break;
            case 2:
                example="具体题目：下列哪些项属于饮料：" +
                        "A.面包" +
                        "B.牛奶" +
                        "C.可乐" +
                        "D.网络浏览器" +
                        "正确答案：BC。" ;
                break;
            case 3:
                example="具体题目：Java是一种编程语言"+
                        "正确答案：True。";
                break;
            default:
                example="具体题目：Java是什么?" +
                        "正确答案：一种编程语言。(字数50以内)";
        }
        String level=new String("");
        switch (question.getLevel()) {
            case 1:
                level="简单";
                break;
            case 2:
                level="普通";
                break;
            case 3:
                level="困难";
                break;
            default:
                level="地狱";
        }
        int bank_id= Integer.parseInt(question.getQuBankId());
        String qubankname= questionBankMapper.selectBankNameById(bank_id);
        question.setQuBankName(qubankname);
        String content=new String("根据下面要求按照题目示例给出试题："+
                "考试科目："+question.getQuBankName()+
                "知识点："+question.getAnalysis()+
                "题目类型："+qutype+
                "题目数量：1"+
                "题目难度："+level+
                "题目示例（包括题目、正确答案和解析部分）：" +
                "请按照以下格式输出:"+
                example+
                "解析：……");
        content="{\"messages\":[{\"role\":\"user\",\"content\":\""+content+"\"}]}";
        System.out.println(content);
        //QuestionRequestImpl questionRequest=new QuestionRequestImpl();
        content=producetest(content).toString();
        content.replace("\n","");
                //.trim();
        System.out.println("剪枝后的content:"+content);
        return content;
    }
    final String API_KEY = "vfuYaB8qaN5pP41tzcGxErjP";
    public  final String SECRET_KEY = "2AwGBxjeIpL5UJmthKJYAK5mIoHXoO2F";

    @Override
    public  String wrongQuestionRequestService(Question question) throws IOException {//根据题目（模板）来生成对应的请求语句
        question.setLevel(2);
        Question wrongQuestion=new Question();
        wrongQuestion.setQuContent(question.getAnalysis());
        String analysis=question.getAnalysis();
        String realAnalysis=resolveAnalysis(analysis);
        question.setAnalysis(realAnalysis);
        wrongQuestion.setQuType(1);
        wrongQuestion.setCreateTime(DateTimeUtil.getCurrentDate());
        wrongQuestion.setCreatePerson(question.getCreatePerson());
        wrongQuestion.setLevel(2);
        wrongQuestion.setImage("");
        wrongQuestion.setQuBankId(question.getQuBankId());
        wrongQuestion.setQuBankName("错题");
        wrongQuestion.setAnalysis(realAnalysis);
        questionMapper.insert(wrongQuestion);
        String qutype=new String("");
        switch (question.getQuType()) {
            case 1:
                qutype="四选一选择题";
                break;
            case 2:
                qutype="四选多选择题";
                break;
            case 3:
                qutype="判断题";
                break;
            default:
                qutype="简答题";
        }
        String example=new String();
        switch (question.getQuType()) {
            case 1:
                example="具体题目：Java是一种：" +"\\n"+
                        "    A. 操作系统" +"\\n"+
                        "    B. 编程语言" +"\\n"+
                        "    C. 数据库管理系统" +"\\n"+
                        "    D. 网络浏览器" +"\\n"+
                        "答案 B。" +"\\n";
                break;
            case 2:
                example="具体题目：Java是一种：" +"\\n"+
                        "    A. 操作系统" +"\\n"+
                        "    B. 编程语言" +"\\n"+
                        "    C. 数据库管理系统" +"\\n"+
                        "    D. 网络浏览器" +"\\n"+
                        "答案 BC。" +"\\n";
                break;
            case 3:
                example="具体题目：Java是一种编程语言"+"\\n"+
                        "答案 True。" +"\\n";
                break;
            default:
                example="具体题目：Java是什么?" +"\\n"+
                        "答案 一种编程语言。(字数50以内)" +"\\n";
        }
        String level=new String("");
        switch (question.getLevel()) {
            case 1:
                level="简单";
                break;
            case 2:
                level="普通";
                break;
            case 3:
                level="困难";
                break;
            default:
                level="地狱";
        }
        switch (question.getQuBankId()){
            case "1":
                question.setQuBankName("小学数学题库");
                break;
            case "2":
                question.setQuBankName("生活小常识");
                break;
            case "5":
                question.setQuBankName("java开发");
                break;
        }
        String content=new String("根据下面要求按照题目示例给出试题："+"\\n"+
                "考试科目："+question.getQuBankName()+"\\n"+
                "知识点："+question.getAnalysis()+"\\n"+
                "题目类型："+qutype+"\\n"+
                "题目数量：1"+"\\n"+
                "题目难度："+level+"\\n"+
                "题目示例（包括题目、正确答案和解析部分）：" +"\\n"+
                "请按照以下格式输出:"+"\\n"+
                example+
                "解析：……");
        content="{\"messages\":[{\"role\":\"user\",\"content\":\""+content+"\"}]}";
        System.out.println("问题题库："+question.getQuBankId());
        System.out.println(content);
//        QuestionRequestImpl questionRequest=new QuestionRequestImpl();
        content=producetest(content).toString();
        content.replace("\n","");
//                .trim();
        return content;
    }

    final static OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder()
             .readTimeout(100, TimeUnit.SECONDS)
             .connectTimeout(100, TimeUnit.SECONDS)
             .build();

    public String producetest(String content) throws IOException {//请求调用Api
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, content);
        Request request = new Request.Builder()
                //.url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_speed?access_token=" + getAccessToken())
                //.url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-func-8k?access_token=" + getAccessToken())
                .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/xp77yno8_questional?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String res= response.body().string();
        System.out.println(res);
        System.out.println("success");
        return res;
    }
    public String resolveAnalysis(String analysis)throws IOException {
        analysis.replace("\\n", "")
                .replace("\n","");
        String content=new String("请用10个字提炼下面这道题的核心知识点,不带分析"+"\\n"+
                analysis
               );
        content="{\"messages\":[{\"role\":\"user\",\"content\":\""+content+"\"}]}";
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, content);
        Request request = new Request.Builder()
                //.url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_speed?access_token=" + getAccessToken())
                .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-func-8k?access_token=" + getAccessToken())

                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String res= response.body().string();
        System.out.println(res);
        System.out.println("success");
        JSONObject jsonObject = new JSONObject(res);
        String originalString = jsonObject.getString("result");
        String prefix = "核心知识点：";
        String extractedString = originalString.substring(prefix.length());
        System.out.println(extractedString);
        return extractedString;
    }
     public  String getAccessToken() throws IOException {//调用
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        try {
            return new JSONObject(response.body().string()).getString("access_token");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
}
